﻿namespace TestProject.FunWithExpressions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Linq.Expressions;

    public class Calculator
    {
        public string Calcul<T>(T data, LambdaExpression query, string format)
        {
            string reportValue;

            if (HasIssue(data, query, out reportValue))
            {
                return reportValue;
            }

            //// executes the aggregates
            //query = (LambdaExpression)ExpressionPreProcessor.PreProcessor(data, query);

            //// checks the rules against the results of the aggregates
            //if (HasIssue(data, query, out reportValue))
            //{
            //    return reportValue;
            //}

            Delegate lambda = query.Compile();
            decimal? result = (decimal?)lambda.DynamicInvoke(data);

            return result != null
                ? result.Value.ToString(format)
                : TypeDonnee.Manquante.ReportValue;
        }

        private bool HasIssue(object data, LambdaExpression query, out string reportValue)
        {
            reportValue = null;

            //var rulesCheckerResult = DomRulesChecker.Check(data, query);
            var rulesCheckerResult = RulesChecker.Check(data, query);

            if (rulesCheckerResult.HasManquante)
            {
                reportValue = TypeDonnee.Manquante.ReportValue;
            }

            if (rulesCheckerResult.HasDivisionParZero)
            {
                reportValue = TypeDonnee.DivisionParZero.ReportValue;
            }

            if (rulesCheckerResult.HasNonDiffusable)
            {
                reportValue = TypeDonnee.NonDiffusable.ReportValue;
            }

            if (rulesCheckerResult.HasConfidentielle)
            {
                reportValue = TypeDonnee.Confidentielle.ReportValue;
            }

            return reportValue != null;
        }
    }
}
